<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{width: 400px;height: 300px;background: #ccc;position: absolute;left:0;top:0;}
        .box h2{margin: 0;line-height: 30px;background: pink;
        padding: 10px 0;cursor:move;}
    </style>
</head>
<body>
    <div class="box">
        <h2>这是标题</h2>
        <div class="cont">
            这是内容区域
        </div>
    </div>
</body>
<script>
    const box=document.querySelector(".box")
    const h2=document.querySelector(".box h2")
    
    const clientW=document.documentElement.clientWidth
    const clientH=document.documentElement.clientHeight;
    h2.onmosedown=function(eve){
        const aaa=eve||window.event;

        document.onmousemove = function(eve){
            // 移动时获取事件对象
            var e = eve || window.event;
            // 计算元素的位置：移动时相对于页面的坐标 - 按下时相对于元素的坐标
            var l = e.pageX - aaa.offsetX;
            var t = e.pageY - aaa.offsetY;
            // 边界限定
            if(l<0) l=0;
            if(t<0) t=0;
            if(l > clientW - obox.offsetWidth) l = clientW - obox.offsetWidth;
            if(t > clientH - obox.offsetHeight) t = clientH - obox.offsetHeight;
            // 将计算并限定之后的位置，设置给元素
            obox.style.left = l + "px"
            obox.style.top = t + "px"
        }
        // 抬起事件
        document.onmouseup = function(){
            // 清除移动和抬起事件
            document.onmousemove = null;
            document.onmouseup = null;
        }

    }


    
    
</script>
</html>